﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using SyncCommon;
using System.Threading;
using System.Web;

namespace SyncWebSite
{
    public class Sync58 : SyncHouseBase
    {
        private string cd;
        private string ptk;
        private string targetID = "";
        private string logintime = "1346058712095";
        private List<string> retImages = new List<string>();
        private Dictionary<string, string> loginCookies;
        private string CityID = "2";
        private string CityShort = "sh";
        public Sync58(string user, string password)
            : base(user, password)
        {

        }

        #region SyncHouseBase
        public override bool CheckLogin()
        {
            string status = InnerLogin();
            if (status.Contains("parent.$.c.Error.setErrorTip"))
            {
                return false;
            }
            return true;
        }

        public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);

            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    error = "登录失败";
                    //UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, true, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityShort(info.City);
                    if (!CheckUserExpired(info, ref error))
                    {
                        goto erroHanlder;
                    }
                    SyncImages(info);


                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = "";
                    GetCityID(info.City);
                    WebRequest request = new WebRequest(GetCityPostPageUrl(info));
                    request.Cookies = loginCookies;
                    string htm = request.GetResouceStr();

                    if (htm.IndexOf("发布信息太过频繁") >= 0)
                    {
                        Thread.Sleep(30000);
                        htm = request.GetResouceStr();
                    }
                    request = new WebRequest(GetPostUrl(info), FormType.MultiPart);
                    request.Cookies = loginCookies;
                    if (htm.IndexOf("验证码") >= 0)
                    {
                        Random r = new Random();
                        string code = this.PrcoessValidationCode("http://post.58.com/code?infoid=0&rnd" + r.Next().ToString());
                        request.AddContent("codeText", code);

                    }
                    request.AddContent("type", "0");
                    request.AddContent("Title", info.Title);

                    request.AddContent("daxue", "");
                    request.AddContent("xianluzhoubian", "");
                    request.AddContent("ditiexian", "");
                    request.AddContent("stationdistance", "");
                    request.AddContent("ditiezhan", "");
                    request.AddContent("gongjiaoxian", "");
                    request.AddContent("busdistance", "");

                    //小区ID映射
                    GetEstateDetail(request, info, htm);
                    GetEstateID(request, info);

                    request.AddContent("dizhi", info.LocalAddress);
                    request.AddContent("diduan", "[|#|@]");
                    request.AddContent("diduan2", "[|#|@]");
                    request.AddContent("huxingting", info.Hall);
                    request.AddContent("huxingwei", info.WashRoom);
                    request.AddContent("Floor", info.CurrentFloor);
                    request.AddContent("zonglouceng", info.Floors);
                    request.AddContent("MinPrice", info.Price);
                    request.AddContent("area", info.Area);
                    request.AddContent("BuildingEra", GetAge(info.Age));
                    request.AddContent("chanquan", info.OwnerShip);
                    request.AddContent("ObjectType", info.HouseType);
                    request.AddContent("fittype",GetDecoration( info.Decoration));
                    request.AddContent("Toward", GetToward(info.Toward));

                    request.AddContent("Content", info.Description);

                    request.AddContent("backFunction", "$.c.Uploader.finish");

                    request.AddContent("Pic", GetImages());

                    request.AddContent("PicDesc", GetImageDes());
                    request.AddContent("PicPos", retImages.Count.ToString());
                    request.AddContent("Phone", info.Mobile);
                    if (info.Name.Length > 6 || info.Name.Length < 2)
                    {
                        error = "发布者姓名必须2-6个字";
                        goto erroHanlder;

                    }
                    request.AddContent("goblianxiren", info.Name);
                    request.AddContent("jushishuru", info.Room);

                    request.AddContent("huxingshi", info.Room);
                    request.AddContent("gobalsokey", info.Title + "|" + info.Estate);
                    request.AddContent("fcookie", "6c0a4665-665f-47dc-af66-6cb75a7e3165");

                    request.AddContent("hiddenTextBoxJoinValue", info.Estate + ":" + info.LocalAddress + ":" + info.Name);
                    request.AddContent("xiaobao_option", "0");

                    status = request.SendWaitString();

                    //<script type="text/javascript">top.location.href = '/postsuccess/0/11015707025032/?postsms=&callsms=0&score=66&phone=&divert=0&call58bb=&tuiguang_option=';</script>
                    loginCookies = request.Cookies;
                    if ((status.ToLower().Contains("http://my.58.com/infopresssuccess")) || (status.ToLower().Contains("postsuccess")))
                    {
                        if (status.ToLower().Contains("postsuccess"))
                        {
                            Regex regex5 = new Regex(@"postsuccess\S*?/(?<id>[\d\s]+?)/\?");
                            if (regex5.IsMatch(status) && !string.IsNullOrEmpty(regex5.Match(status).Groups["id"].Value ?? ""))
                            {
                                targetID = regex5.Match(status).Groups["id"].Value ?? "";
                            }
                        }
                        else
                        {
                            Regex regex6 = new Regex(@"infoid=(\d+)");
                            if (regex6.IsMatch(status))
                            {
                                Match match3 = regex6.Match(status);
                                targetID = match3.Groups[0].Value;
                            }
                        }

                        string url = "http://" + CityShort + ".58.com/ershoufang/" + targetID + "x.shtml";
                        UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, url);
                        return true;
                    }
                    else
                    {
                        Regex regex = new Regex(@"alert\(\'(?<msg>[\s\S]*?)\'\)");
                        Match ma = regex.Match(status);

                        if (ma.Success)
                        {
                            error = ma.Groups["msg"].Value;
                        }
                        else
                        {
                            if (status.IndexOf("parent.$.c.Error") > -1)
                            {
                                Regex regex2 = new Regex(@"'msg':\['([\s\S]*)'\]");
                                Match match = regex2.Match(status);
                                if (match.Success)
                                {
                                    if (match.Groups.Count > 1)
                                    {
                                        error = HtmlHelper.RemoveHtmlCode(match.Groups[1].Value);
                                    }
                                    else
                                    {
                                        error = HtmlHelper.RemoveHtmlCode(match.Groups[0].Value);
                                    }
                                }
                                if (!string.IsNullOrEmpty(error) && error.Contains("maxpostcount"))
                                {
                                    error = "你今天的发布数量已经满了。";
                                }
                                else
                                {
                                    Regex regex4 = new Regex(@"showError\(\'(?<ErrorInfo>\S*)\'\)");
                                    if (regex4.IsMatch(status))
                                    {
                                        error = HtmlHelper.RemoveHtmlCode(regex4.Match(status).Groups["ErrorInfo"].Value);
                                    }
                                }
                            }
                            else
                            {
                                if (status.Contains("var errorInfo"))
                                {
                                    Regex regex3 = new Regex(@"'msg':\['([\s\S]*)'\]");
                                    if (status.Contains("您发布信息太过频繁"))
                                    {
                                        error = "您发布信息太过频繁。";
                                    }
                                    if (status.Contains("maxpostcount"))
                                    {
                                        error = "你今天的发布数量已经满了。";
                                    }
                                    if (string.IsNullOrEmpty(error))
                                    {
                                        ma = regex3.Match(status);
                                        if (ma.Success)
                                        {
                                            error = ma.Groups[0].Value;
                                        }
                                    }
                                }
                                else
                                {
                                    error = "网站提交错误";
                                    LogCenter.LogMessage("网站提交(58同城)特别错误" + status);
                                }
                            }
                        }
                    }
                }

            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("58同城信息提交", exp);
                error = exp.Message;
            }
            
        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);

            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    error = "登录失败";
                    //UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityShort(info.City);
                    if (!CheckUserExpired(info, ref error))
                    {
                        goto erroHanlder;
                    }

                    SyncImages(info);

                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = "";
                    GetCityID(info.City);
                    WebRequest request = new WebRequest(GetCityPostPageUrl(info));
                    request.Cookies = loginCookies;
                    string htm = request.GetResouceStr();

                    if (htm.IndexOf("发布信息太过频繁") >= 0)
                    {
                        Thread.Sleep(30000);
                        htm = request.GetResouceStr();
                    }
                    request = new WebRequest(GetPostUrl(info), FormType.MultiPart);
                    request.Cookies = loginCookies;
                    if (htm.IndexOf("验证码") >= 0)
                    {
                        string code = this.PrcoessValidationCode(htm);
                        request.AddContent("codeText", code);
                    }
                    #region Rent Related Information
                    request.AddContent("bianhao", "");
                    request.AddContent("IsBiz", "1");//中介
                    request.AddContent("EffectiveDate", "365");
                    request.AddContent("HireType", info.HireType);//租借形式
                    GetHireTypeOhterSetting(info, request);
                    request.AddContent("fukuanfangshi", GetPaymentType(info.PayType));
                    request.AddContent("ruzhushijian", "立即入住");
                    request.AddContent("MinPrice", info.MonthPrice);
                    #endregion

                    request.AddContent("type", "0");
                    request.AddContent("Title", info.Title);

                    request.AddContent("daxue", "");
                    request.AddContent("xianluzhoubian", "");
                    request.AddContent("ditiexian", "");
                    request.AddContent("stationdistance", "");
                    request.AddContent("ditiezhan", "");
                    request.AddContent("gongjiaoxian", "");
                    request.AddContent("busdistance", "");

                    request.AddContent("selectDiduanHidden", "2995");


                    //小区ID映射
                    GetEstateDetail(request, info, htm);
                    GetEstateID(request, info);

                    MapHouseAllocation(request, info);

                    request.AddContent("dizhi", info.LocalAddress);
                    request.AddContent("diduan", "[|#|@]");
                    request.AddContent("diduan2", "[|#|@]");
                    request.AddContent("huxingting", info.Hall);
                    request.AddContent("huxingwei", info.WashRoom);
                    request.AddContent("Floor", info.CurrentFloor);
                    request.AddContent("zonglouceng", info.Floors);

                    request.AddContent("area", info.Area);
                    request.AddContent("BuildingEra", GetAge(info.Age));
                    request.AddContent("chanquan", info.OwnerShip);
                    request.AddContent("ObjectType", info.HouseType);
                    request.AddContent("fittype", GetDecoration(info.Decoration));
                    request.AddContent("Toward", GetToward(info.Toward));

                    request.AddContent("Content", info.Description);

                    request.AddContent("backFunction", "$.c.Uploader.finish");

                    request.AddContent("yijuhua", info.SearchKey);
                    request.AddContent("Pic", GetImages());

                    request.AddContent("PicDesc", GetImageDes());
                    request.AddContent("PicPos", retImages.Count.ToString());
                    request.AddContent("Phone", info.Mobile);
                    request.AddContent("goblianxiren", info.Name);

                    if (info.Name.Length > 6 || info.Name.Length < 2)
                    {
                        error = "发布者姓名必须2-6个字";
                        goto erroHanlder;

                    }
                    request.AddContent("jushishuru", info.Room);

                    request.AddContent("huxingshi", info.Room);
                    request.AddContent("gobalsokey", info.Title + "|" + info.Estate);
                    request.AddContent("fcookie", "6c0a4665-665f-47dc-af66-6cb75a7e3165");

                    request.AddContent("hiddenTextBoxJoinValue", info.Estate + ":" + info.LocalAddress + ":" + info.Name);
                    request.AddContent("xiaobao_option", "0");

                    status = request.SendWaitString();

                    //<script type="text/javascript">top.location.href = '/postsuccess/0/11015707025032/?postsms=&callsms=0&score=66&phone=&divert=0&call58bb=&tuiguang_option=';</script>
                    loginCookies = request.Cookies;
                    if ((status.ToLower().Contains("http://my.58.com/infopresssuccess")) || (status.ToLower().Contains("postsuccess")))
                    {
                        if (status.ToLower().Contains("postsuccess"))
                        {
                            Regex regex5 = new Regex(@"postsuccess\S*?/(?<id>[\d\s]+?)/\?");
                            if (regex5.IsMatch(status) && !string.IsNullOrEmpty(regex5.Match(status).Groups["id"].Value ?? ""))
                            {
                                targetID = regex5.Match(status).Groups["id"].Value ?? "";
                            }
                        }
                        else
                        {
                            Regex regex6 = new Regex(@"infoid=(\d+)");
                            if (regex6.IsMatch(status))
                            {
                                Match match3 = regex6.Match(status);
                                targetID = match3.Groups[0].Value;
                            }
                        }
                        string url = "http://" + CityShort + ".58.com/zufang/" + targetID + "x.shtml";
                        UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, url);
                        return true;
                    }
                    else
                    {
                        Regex regex = new Regex(@"alert\(\'(?<msg>[\s\S]*?)\'\)");
                        Match ma = regex.Match(status);

                        if (ma.Success)
                        {
                            error = ma.Groups["msg"].Value;
                        }
                        else
                        {
                            if (status.IndexOf("parent.$.c.Error") > -1)
                            {
                                Regex regex2 = new Regex(@"'msg':\['(?<errorMessage>[\s\S]*)'\]");
                                Match match = regex2.Match(status);
                                if (match.Success)
                                {
                                    error = HtmlHelper.RemoveHtmlCode(match.Groups["errorMessage"].Value);
                                }
                                if (!string.IsNullOrEmpty(error) && error.Contains("maxpostcount"))
                                {
                                    error = "你今天的发布数量已经满了。";
                                }
                                else
                                {
                                    Regex regex4 = new Regex(@"showError\(\'(?<ErrorInfo>\S*)\'\)");
                                    if (regex4.IsMatch(status))
                                    {
                                        error = HtmlHelper.RemoveHtmlCode(regex4.Match(status).Groups["ErrorInfo"].Value);
                                    }
                                }
                            }
                            else
                            {
                                if (status.Contains("var errorInfo"))
                                {
                                    Regex regex3 = new Regex(@"'msg':\['([\s\S]*)'\]");
                                    if (status.Contains("您发布信息太过频繁"))
                                    {
                                        error = "您发布信息太过频繁。";
                                    }
                                    if (status.Contains("maxpostcount"))
                                    {
                                        error = "你今天的发布数量已经满了。";
                                    }
                                    if (string.IsNullOrEmpty(error))
                                    {
                                        ma = regex3.Match(status);
                                        if (ma.Success)
                                        {
                                            error = ma.Groups[0].Value;
                                        }
                                    }
                                }
                                else
                                {
                                    error = "网站提交错误";
                                    LogCenter.LogMessage("网站提交(58同城)特别错误" + status);
                                }
                            }
                        }

                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("58同城信息提交", exp);
                error = exp.Message;
            }

        erroHanlder:
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            //添加根据合发码查找 发布号的代码
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {
                if (CheckLogin())
                {
                    WebRequest request = new WebRequest("http://my.58.com/submit/infopost/?op=close", FormType.FormUrlEncode);
                    request.Cookies = loginCookies;
                    request.AddContent("ids", targetID);
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = request.SendWaitString();
                    if (status.Contains("closeinfosuccess"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess, "5分钟后生效");
                        return true;
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "删除失败");
                        LogCenter.LogMessage("删除信息失败。提交值ID:" + targetID ?? "" + "返回值:" + status ?? "");
                        return false;
                    }
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登陆失败");
                    return false;
                }
            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }

        public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        {
            return DeleteRentHouse(info, targetID);
        }

       

        public override bool RefreshRentHouse(HouseInfo info, string targetID)
        {
            //添加根据合发码查找 发布号的代码
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {
                if (CheckLogin())
                {
                    WebRequest request = new WebRequest("http://my.58.com/inforefresh", FormType.FormUrlEncode);
                    request.Cookies = loginCookies;
                    request.AddContent("ids", targetID);
                    request.AddContent("paytype", "1");
                    UpdateCurrentStatus(StandardProgress.PosData);
                    string status = request.SendWaitString();
                    if (status.Contains("成功刷新"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess, "");
                        return true;
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "刷新失败。请检查是否刷新限额已满");
                        return false;
                    }
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登陆失败");
                    return false;
                }
            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }
        public override bool RefreshSaleHouse(HouseInfo info, string targetID)
        {
            return RefreshRentHouse(info, targetID);
        }
        
        #endregion

        #region HelpFunction

        /// <summary>
        /// 匹配房间配置。比如电视 热水器等.
        /// 租房使用。待完成
        /// </summary>
        /// <param name="postData"></param>
        private void MapHouseAllocation(WebRequest request, HouseInfo info)
        {
            try
            {

            }
            catch
            {
            }

        }

        public void GetCityShort(string CityName)
        {
            if (CityName == "上海")
            {
                CityShort = "sh";
            }
        }

        public void SyncImages(HouseInfo info)
        {
            retImages.Clear();
            errorImage = 0;
            if (info.Images != null&& info.Images.Length>0)
            {
                string status = "";
                foreach (string url in info.Images)
                {
                    try
                    {
                        WebRequest request = new WebRequest(url);
                        Stream stream = request.GetResouce();
                        string name = url.Substring(url.LastIndexOf('/') + 1);
                        request = new WebRequest("http://image.58.com/postpic/upload", FormType.MultiPart);
                        request.AddContent("PicPos", "1");
                        request.AddContent("backFunction", "$.c.Uploader.finish");
                        request.AddFile(name, stream);
                        string k = request.SendWaitString();
                        Regex reg = new Regex("(?<=\')/p1/big/.*?(?=\')");
                        Match ma = reg.Match(k);
                        if (ma.Success)
                        {
                            status = status + ma.Value + "\r\n";
                            retImages.Add(ma.Value);
                        }
                        else
                        {
                            errorImage++;
                        }
                    }
                    catch (Exception exp)
                    {
                        errorImage++;
                    }
                    //<script language="javascript">document.domain="58.com"; parent.$.c.Uploader.finish(1, '/p1/big/n_21432951094029.jpg', 1);</script>
                }

            }
        }

        public string InnerLogin()
        {
            WebRequest request = new WebRequest("http://passport.58.com/login");
            string k = request.GetResouceStr();
            Regex reg = new Regex(@"(?<= id\=""cd"" value="")\d*?(?="")");
            Match ma = reg.Match(k);
            if (ma.Success)
            {
                cd = ma.Value;
                //int.TryParse(ma.Captures[0].Value , out cd);
            }
            reg = new Regex(@"(?<= id\=""ptk"" value="").*?(?="")");
            ma = reg.Match(k);
            if (ma.Success)
            {
                ptk = ma.Value;
            }

            request = new WebRequest("https://passport.58.com/dounionlogin", FormType.FormUrlEncode);
            request.AddStringCookies("58home=sh; city=sh; id58=05eNElAENKMZ0na1aVrLAg==; __utma=253535702.346512587.1342452896.1342452896.1342458997.2; __utmz=253535702.1342452896.1.1.utmcsr=baidu|utmccn=(organic)|utmcmd=organic|utmctr=58; myfeet_tooltip=end; bangtoptipclose=1; __utmc=253535702; __utmb=253535702.3.10.1342458997; ipcity=sh%7C%u4E0A%u6D77");

            string encode = string.Format("isweak=0&path=http%3A%2F%2Fpost.58.com%2F2%2F12%2Fs5%3Fpts%3D1346059702714&p1={0}&p2={1}&timesign={2}&ptk={3}&cd={4}&username={5}&password=password",
             MD58Cal(Password, logintime), MD58Cal_16(Password, logintime), logintime, ptk, cd, UserName);
            request.AddPureStr(encode);
            loginCookies = request.Cookies;
            return request.SendWaitString();
        }

        public string GetCityPostPageUrl(HouseInfo info)
        {
            string site = GetSiteCode(info);
            if (info.TradeType == TradeType.Rent)
            {
                return "http://post.58.com/" + site + "/8/s5";
            }
            else
            {
                return "http://post.58.com/" + site + "/12/s5";
            }
        }

        private string PrcoessValidationCode( string html)
        {
            //$.c.verifycode.showVerifyCode(0);
            Regex reg = new Regex("verifycode.showVerifyCode\\((?<code>\\d*?)\\)");
            string id ="0";
            if (reg.IsMatch(html))
            {
                id = reg.Match(html).Groups["code"].Value;
            }
            Random r = new Random();
            string url = string.Format("http://post.58.com/code?infoid={0}&rnd={1}",id,r.Next().ToString());
            string loginCodeUrl = url;// "http://post.58.com/code";
            WebRequest request = new WebRequest(url);
            request.Cookies = loginCookies;
            //验证码处理代码待加
            return GetValidationCode(request.GetResouce());
        }

        public string GetSiteCode(HouseInfo info)
        {
            string site = "2";
            if (info.City == "上海")
            {
                site = "2";
            }
            return site;
        }

        /// <summary>
        /// 获取58的付款方式
        /// </summary>
        /// <param name="current"></param>
        /// <returns></returns>
        public string GetPaymentType(string current)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 0:面议 1:押一付三 3:押一付一 8:押二付一 6:半年付 7:年付
            if (string.IsNullOrEmpty(current))
            {
                return "0";
            }
            switch (current)
            { 
                case "0":
                    return "0";
                case "2":
                    return "1";
                case "1":
                    return "3";
                case "3":
                    return "1";
                case "4":
                    return "6";
                case "5":
                    return "7";
                default:
                    return "0";
            }

        }
        public string GetDecoration(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 1.毛坯 2.简单装修 3.中等装修 4.精装修 5.豪华装修
            if (dec == "1")
            {
                return "1";
            }
            if (dec == "2")
            {
                return "2";
            }
            if (dec == "3")
            {
                return "4";
            }
            if (dec == "4")
            {
                return "5";
            }
            return "2";
        }
        public string GetToward(string toward)
        {
            //当前 1=东 2=南 3=西 4=北 5=南北 6=东西 7=东南 8=西南 9=东北 10=西北 11=其他
            //目标 1=东 2=南 3=西 4=北 5=南北 6=东西 7=东南 8=西南 9=东北 10=西北
            if (toward == "11")
                return "1";
            return toward;
        }

        public void GetHireTypeOhterSetting(HouseInfo info, WebRequest request)
        {
            if (info.HireType == "0" || info.HireType == "1")
            {
                ///房源银行没有单间信息
                request.AddContent("woshi", "1");
                request.AddContent("xianzhi", "1");
            }
        }

        public string GetPostUrl(HouseInfo info)
        {
            return GetCityPostPageUrl(info) + "/submit";
        }

        private void GetEstateID( WebRequest subRequest,HouseInfo info)
        {
            try
            {
                string uploadUrl = "http://post.58.com/ajax?&action=getxiaoquinfo&cityid=" + CityID + "&xq=" + HttpUtility.UrlEncode(info.Estate) + "&rand=";
                WebRequest request = new WebRequest(uploadUrl);
                string ret = request.GetResouceStr();
                Regex reg = new Regex(@"\$xq_(?<id>[\d\s]*?)\$");
                Match ma = reg.Match(ret);
                if (ma.Success)
                {
                    subRequest.AddContent("xiaoqu", ma.Groups["id"].Value.Trim());
                }
                else
                {
                    subRequest.AddContent("xiaoqu", info.Estate);
                    subRequest.AddContent("xiaoqu_view", info.Estate);
                }
            }
            catch (Exception exception)
            {  
                LogCenter.Log("获取小区ID异常(58同城)", exception);
                throw new UnMatchEstateException(info.Estate);
            }
        }

        private bool CheckUserExpired(HouseInfo info,ref string error)
        {
          
            try
            {
                string strUrl = "http://vip.58.com/infopost/" + GetSiteCode(info) + "/8/";
                WebRequest request = new WebRequest(strUrl);
                request.Cookies = loginCookies;
                string str2 = request.GetResouceStr();
                if (((str2 != null) && (str2 != "")) && (str2.Contains("您的网邻通服务已到期，不能使用该功能") && str2.Contains("退出")))
                {
                    error = "您的网邻通服务已到期，不能使用该功能";
                    return false;
                }
            }
            catch (Exception exception)
            {
                LogCenter.Log("判断网邻通(58)异常", exception);
            }
            return true;
        }




        private void GetEstateDetail(WebRequest subRequest, HouseInfo info, string retHtml)
        {

            Random random = new Random();
            string strUrl;
            if (random.NextDouble() > 0.5)
            {
                strUrl = "http://211.151.64.39:8080";
            }
            else
            {
                strUrl = "http://211.151.77.230:8080";
            }
            strUrl = strUrl + "/searchsuggest_6.do?";
            strUrl = strUrl + "inputbox=" + HttpUtility.UrlPathEncode(info.Estate) + "&cityid=" + CityID + "&catid=12&type=1&callback=callback" + random.Next(1000, 9999).ToString();
            WebRequest request = new WebRequest(strUrl);
            string html = request.GetResouceStr();

            string pattern = "\"k\": \"(?<name>[\\S\\s]*?)\", \"s\": \"(?<address>[\\S\\s]*?)\", \"r\":(?<rValue>[\\S\\s]*?), \"m\":(?<mValue>[\\S\\s]*?),";
            Regex regex = new Regex(pattern);
            Match match = regex.Match(html);
            if (match.Success)
            {

                subRequest.AddContent("localArea", match.Groups["rValue"].Value.Trim());
                subRequest.AddContent("localDiduan", match.Groups["mValue"].Value.Trim());
            }
            else
            {
                Regex reg = new Regex(@"<option value=""(?<districtID>\d*)""\s*>" + info.LocalDistrict + "</option>");

                if (reg.IsMatch(retHtml))
                {
                    subRequest.AddContent("localArea", reg.Match(retHtml).Groups["districtID"].Value);
                    Regex reg2 = new Regex(@"<option id='" + reg.Match(retHtml).Groups["districtID"].Value + @"_\d*' value='(?<diduanID>\d*)'>" + info.LocalDiduan + "</option>");
                    if (reg2.IsMatch(retHtml))
                    {
                        subRequest.AddContent("localDiduan", reg2.Match(retHtml).Groups["diduanID"].Value);
                    }
                    else
                    {
                    throw new UnFindDiduanException(info.LocalDiduan);
                    }
                }
                else
                {
                    throw new UnFindDistrictException(info.LocalDistrict);
                }
                
               
            }
        }


        private void GetCityID(string cityName)
        {
            try
            {
                string input = "";
                WebRequest request = new WebRequest("http://post.58.com/postindex.htm");
                string ret = request.GetResouceStr();
                
                if (!string.IsNullOrEmpty(cityName))
                {
                    Regex regex = new Regex("<a href=\"\\S*?/(?<cityid>[\\s\\d]*?)/\"(\\s*?class=\"lr\")?\\s*?onclick\\S*?>" + cityName + "</a>");
                    if (regex.IsMatch(input))
                    {
                        this.CityID = regex.Match(input).Groups["cityid"].Value.Trim();
                    }
                }
            }
            catch (Exception exp)
            {
                LogCenter.Log("无法获取到目标城市代码,城市:" + cityName, exp);
            }
        }



        private string MD58Cal(string input, string time)
        {
            return CalculateMD5Hash(CalculateMD5Hash(input) + time.Substring(5, 6));
        }
        private string MD58Cal_16(string input, string time)
        {
            //string k = string.Join("", CalculateMD5Hash(input).Substring(8, 16).Reverse<char>());
            string k = ReverseString(CalculateMD5Hash(input).Substring(8, 16));
            return CalculateMD5Hash(k + time.Substring(5, 6));
        }

        private string ReverseString(string k)
        {
            StringBuilder builder = new StringBuilder();
            for (int index = k.Length - 1; index >= 0; index--)
            {
                builder.Append(k[index]);
            }
            return builder.ToString();
        }

        private string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        private string GetImages()
        {
            return string.Join("|", retImages.ToArray());
        }

        private string GetImageDes()
        {
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < retImages.Count; index++)
            {
                builder.Append("|");
            }
            return builder.ToString();
        }

        public string GetAge(string age)
        {
            int temp = 1;
            int.TryParse(age, out temp);
            return (DateTime.Now.Year - temp).ToString();
        }
        #endregion

        public override bool CheckTitle(HouseInfo infor, bool isSale, ref string errorInfor)
        {
            if (string.IsNullOrEmpty(infor.Title))
            {
                errorInfor = "标题不能为空";
                return false;
            }
            if (isSale)
            {
                if (infor.Title.Length < 6
                    || infor.Title.Length > 25)
                {
                    errorInfor = "标题必须6-25字，不能包括电话等信息";
                    return false;
                }
            }
            else
            {
                if (infor.Title.Length < 8
                 || infor.Title.Length > 28)
                {
                    errorInfor = "标题必须8-28字，不能包括电话等信息";
                    return false;
                }
            }
            return true;
        }
        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                if (CheckLogin())
                {
                    if (info.TradeType == TradeType.Sale)
                    {
                        string post = "http://post.58.com/2/12/s5";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            if (k.Key == "58passport")
                            {
                                WebBrowserOp.InternetSetCookie("https://passport.58.com/dounionlogin", k.Key, k.Value);
                            }
                            else
                            {
                                WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                            }
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Sale_Completed);
                    }
                    else
                    {
                        string post = "http://post.58.com/2/8/s5";
                        foreach (KeyValuePair<string, string> k in loginCookies)
                        {
                            if (k.Key == "58passport")
                            {
                                WebBrowserOp.InternetSetCookie("https://passport.58.com/dounionlogin", k.Key, k.Value);
                            }
                            else
                            {
                                WebBrowserOp.InternetSetCookie(post, k.Key, k.Value);
                            }
                        }
                        op.HouseInformation = info;
                        op.Navigate(post);
                        op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Rent_Completed);
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                op.Navigate("http://www.58.com/");
            }
            return true;
        }
        void op_Sale_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.CheckByID("biz", true);
       
            cl.SetValueByID("xiaoqu", info.Estate);

            cl.SetValueByID("dizhi",info.LocalAddress);
     
            cl.SetValueByID("jushishuru",info.Room );
            cl.SetValueByID("huxingting", info.Hall);
            cl.SetValueByID("huxingwei", info.WashRoom);
            cl.SetValueByID("area", info.Area);
            cl.SetValueByID("MinPrice", info.Price);


            cl.SelectByID_Value("ObjectType", info.HouseType);
            cl.SelectByID_Value("fittype", GetDecoration(info.Decoration));
            cl.SelectByID_Value("Toward", GetToward(info.Toward));
            cl.SelectByID_Value("chanquan", info.OwnerShip);
            cl.SetValueByID("jianzhuniandai", info.Age);
            cl.SetValueByID("Floor", info.CurrentFloor);
            cl.SetValueByID("zonglouceng", info.Floors);
            cl.SetValueByID("Title", info.Title);


            cl.SetValueByID("yijuhuaguanggao", info.SearchKey);
            cl.SetValueByID("Content",info.Description);
            cl.SetValueByID("Phone", info.Mobile);
            cl.SetValueByID("goblianxiren", info.Name);
        }
        void op_Rent_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            cl.CheckByName("isBiz", true);

            cl.SetValueByID("xiaoqu", info.Estate);

            cl.SetValueByID("dizhi", info.LocalAddress);

            cl.SetValueByID("jushishuru", info.Room);
            cl.SetValueByID("huxingting", info.Hall);
            cl.SetValueByID("huxingwei", info.WashRoom);
            cl.SetValueByID("area", info.Area);

            cl.SetValueByID("MinPrice", info.MonthPrice);
            cl.SelectByID_Value("fukuanfangshi", GetPaymentType(info.PayType));

            cl.SelectByID_Value("ObjectType", info.HouseType);
            cl.SelectByID_Value("fittype", GetDecoration(info.Decoration));
            cl.SelectByID_Value("Toward", GetToward(info.Toward));

            
            cl.SetValueByID("Floor", info.CurrentFloor);
            cl.SetValueByID("zonglouceng", info.Floors);
            cl.SetValueByID("Title", info.Title);


            cl.SetValueByID("yijuhua", info.SearchKey);
            cl.SetValueByID("Content", info.Description);
            cl.SetValueByID("Phone", info.Mobile);
            cl.SetValueByID("goblianxiren", info.Name);
        }
        #endregion
    }
}
